package com.pearl.jacksonspringboot.demo.dict;

import cn.hutool.core.collection.CollUtil;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.util.NameTransformer;
import com.pearl.jacksonspringboot.demo.ser.Jackson2NullValueSerializer;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 集成``
 *
 * @author TD
 * @version 1.0
 * @date 2024/4/16
 */
public class DictBeanSerializerModifier extends BeanSerializerModifier {

    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        // 1. 创建新的属性集合
        List<BeanPropertyWriter> newBeanProperties = CollUtil.newArrayList(beanProperties);
        // 2. 循环所有属性
        for (BeanPropertyWriter propertyWriter : beanProperties) {
            // 3. 获取注解 @Dict
            Dict annotation = propertyWriter.getAnnotation(Dict.class);
            if (annotation == null) {
                annotation = propertyWriter.getContextAnnotation(Dict.class);
            }
            if (annotation != null) {
                // 4. 新建一个虚拟属性（名称为：添加了注解的属性名+指定后缀）
                NameTransformer transformer = NameTransformer.simpleTransformer("", annotation.suffix());
                BeanPropertyWriter newProperty = propertyWriter.rename(transformer);
                CommonEnum commonEnum = null;
                Class<? extends CommonEnum> using = annotation.using();
                // 5. 获取枚举示例（无法反射，所以直接 IF 判断）
                if (GenderEnum.class.isAssignableFrom(using)) {
                    commonEnum = GenderEnum.MAN;
                }
                // 6. 设置虚拟属性的序列化器
                newProperty.assignSerializer(new DictJsonSerializer(commonEnum));
                newBeanProperties.add(newProperty);
            }
        }
        return newBeanProperties;
    }
}
